<?php

namespace App\Http\Api\Controllers;

use App\Exceptions\BadRequest as BadRequestException;
use App\Repos\Agency;
use App\Repos\Course;
use App\Repos\CourseAgencies;
use App\Services\Logic\Agency\AgencyList;
use App\Services\Logic\Teacher\TeacherList as TeacherListService;
use Phalcon\Mvc\Dispatcher;

/**
 * @RoutePrefix("/api/agency")
 */
class AgencyController extends \App\Http\Api\Controllers\Controller
{

    /**
     * @Get("/index", name="api.agency.index")
     */
    public function indexAction()
    {
        $service = new AgencyList();

        $pager = $service->handle();

        return $this->jsonPaginate($pager);
    }

    /**
     * @Post("/add", name="api.agency.add")
     */
    public function addAction()
    {

    }

    /**
     * @Post("/{id:[0-9]+}/edit", name="api.agency.edit")
     */
    public function editAction($id)
    {

    }


    /**
     * @Get("/{id:[0-9]+}/info", name="api.agency.info")
     */
    public function infoAction($id)
    {
        $articleRepo = new \App\Repos\Agency();

        $article = $articleRepo->findById($id);


        if ($article->deleted == 1) {
            $this->notFound();
        }

        if (!$article) {
            throw new BadRequestException('agency.not_found');
        }


        $courseIds = [];
        $courseAgencyObj = new CourseAgencies();
        $results = $courseAgencyObj->findByAgencyId([$id]);
        foreach ($results as $v) {
            array_push($courseIds, $v->course_id);
        }

        $agencyCourseObj = new Course();
        $courseList = $agencyCourseObj->findByIds($courseIds);
        $results = [];
        foreach ($courseList as $k => $v) {
            if ($v->published == 0) {
                continue;
            }
            $results[] = $v;
        }


        $lists = [];
        $agency = [
            'id'          => $article->id,
            'title'       => $article->title,
            'content'     => $article->content,
            'cover'       => $article->cover,
            'course_list' => $results
        ];
        return $this->jsonSuccess(['agency' => $agency]);
    }

    /**
     * @Post("/{id:[0-9]+}/delete", name="api.agency.delete")
     */
    public function deleteAction($id)
    {

    }


}